<template>
  <div>
    <el-table :data="data" v-loading="loading" stripe>
      <el-table-column v-for="({ label, prop, template, tooltip }) in columns" :key="prop" :prop="prop" :label="label"
        :show-overflow-tooltip="tooltip ?? true">
        <template #default="scope" v-if="template">
          <slot :scope="scope" :name="prop" />
        </template>
        <template #default="scope" v-else>
          {{ scope.row[prop] || '-' }}
        </template>
      </el-table-column>
    </el-table>
    <div v-if="total > 0" class="flex-end-center mt-20">
      <el-pagination v-model:current-page="page.pageNo" v-model:page-size="page.pageSize" :page-sizes="pageSizes"
        background :layout="layout" @current-change="onCurrentChange" @size-change="onSizeChange" :total="total" />
    </div>
  </div>
</template>

<script setup>
import { computed } from "vue"
import { ref } from "vue"
defineOptions({
  name: "ETable"
})
defineProps({
  loading: {
    type: Boolean,
    default: false
  },
  columns: {
    required: true,
    type: Array
  },
  data: {
    type: Array,
    default: () => []
  },
  total: {
    type: Number,
    default: 0
  },
  pageSizes: {
    type: Array,
    default: () => [10, 20, 50, 100, 200]
  },
  layout: {
    type: String,
    default: 'total, sizes, prev, pager, next, jumper'
  }
})

const emit = defineEmits(['onPageChange'])

const page = ref({
  pageNo: 1,
  pageSize: 10
})
const initPageNo = () => {
  page.value.pageNo = 1
}

const pageNo = computed(() => page.value.pageNo)
const pageSize = computed(() => page.value.pageSize)

defineExpose({
  pageNo,
  pageSize,
  initPageNo
})

// 不能使用onChange事件同时处理pageNo和pageSize的变化。因为父组件调用initPageNo会触发onChange事件，导致再次调用emit
const onCurrentChange = (pageNo) => {
  emit('onPageChange', pageNo, pageSize)
}
const onSizeChange = (pageSize) => {
  emit('onPageChange', pageNo, pageSize)
}

</script>

<style lang="scss" scoped></style>